package magicboard.classifier.feature
{

	import magicboard.classifier.Classifier;
	import magicboard.classifier.feature.features.FeatureExtractor;
	import magicboard.model.InkStroke;
	
	public class FeatureClassifier implements Classifier
	{
		// --------------------------------------------------------------------------------------------
		public function FeatureClassifier(){
			
			initPatterns();
		}
		
		// --------------------------------------------------------------------------------------------
		/**
		 * Algorithm
		 * 1. Extract features from the stroke
		 * 2. Create feature vector 
		 * 3. Find pattern similar to feature vector
		 * 
		 * @return Stroke with recognized type
		 */
		public function classify(input:InkStroke):String{	
			
			var features:Object;
			var type:String;
			
			// Extract features
			features = extractFeatures(input);
			type = recognize(features);
			
	  	return type;
		}

		// --------------------------------------------------------------------------------------------
		/** 
		 * @Return map with features 
		 */
		private function extractFeatures(stroke:InkStroke):Object{
			var features:Object = new Object();
			
			trace("Features value:");
			for each(var fe:FeatureExtractor in FeatureExtractor.extractors){
				features[fe.id] = fe.extract(stroke);
				trace(fe.id + ": " + features[fe.id]); 
			}
			
			return features;
		}
		
		// --------------------------------------------------------------------------------------------
		private function recognize(features:Object):String{

			for each(var pattern:Pattern in _patterns){
				if(pattern.distance(features) < 0.2)
					return pattern.name;
			}
			
			return "Unknown";
		}
		
		// --------------------------------------------------------------------------------------------
		/**
		 * Read patters from database
		 */
		private function initPatterns():void{
			
			_patterns = Pattern.createAllPatterns();;
		}
		
		// --------------------------------------------------------------------------------------------
		// Private members
		private var _patterns:Array;
	}
}